//go:build linux || darwin

package utils

import (
	"fmt"
	"gitee.com/simple-set/simple.proxy/src/config"
	"log/slog"
	"os"
	"os/exec"
	"syscall"
)

func InitDaemon() {
	if config.Config.Daemon {
		if pid, err := ForkDaemon(); err == nil {
			slog.Info(fmt.Sprintf("proxy [PID] %d running...", pid))
			os.Exit(0)
		} else {
			slog.Error("ForkDaemon failed", "err", err)
		}
	}
}

// ForkDaemon 启动daemon模式(类unix系统), go不支持fork, 只能启动新进程, 设置SessionId, 绑定输出输出, 以实现脱离当前终端
func ForkDaemon() (int, error) {
	// 设置守护进程启动参数, 移除daemon参数, 避免死循环
	procArgs := make([]string, 0)
	for _, arg := range os.Args {
		if arg != "--daemon" {
			procArgs = append(procArgs, arg)
		}
	}
	// 启动daemon进程
	command := exec.Command(os.Args[0], procArgs[1:]...)
	command.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
	if err := command.Start(); err != nil {
		return 0, err
	} else {
		return command.Process.Pid, nil
	}
}
